package com.onethinker.controller;

import com.alibaba.fastjson.JSONObject;
import com.onethinker.service.impl.UploadPicFactory;
import com.onethinker.service.UploadPicService;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: yangyouqi
 * @Date: 2022/4/2 15:15
 * @Description: 上传控制类
 */
@RestController
@RequestMapping(value = "/api")
@CrossOrigin
public class UploadController {

    @Resource
    private UploadPicFactory uploadPicFactory;

    /**
     * 可上传一张或多张图片信息到不同来源
     * @param request
     * @return
     */
    @RequestMapping(value = "/v1/upload/pic",method = {RequestMethod.POST,RequestMethod.OPTIONS})
    public JSONObject uploadPic(HttpServletRequest request) {
        // 获取form-data参数信息
        JSONObject uploadObj = getRequestParamsObj(request);
        // 获取到具体的上传配置
        UploadPicService uploadPicService = uploadPicFactory.getUploadPicService(uploadObj.getString("type"));
        // 上传图片信息
        return uploadPicService.uploadPic(request,uploadObj.getString("path"));
    }

    private JSONObject getRequestParamsObj(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();

        JSONObject uploadObj = new JSONObject();
        for (Map.Entry<String, String[]> map : parameterMap.entrySet()) {
            uploadObj.put(map.getKey(),map.getValue()[0]);
        }
        System.out.println("上传的JSON：" + uploadObj.toJSONString());
        return uploadObj;
    }
}
